{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# 池化层\n",
    "\n",
    "本节将介绍*池化*（pooling）层，它具有目的：类似于数据增强，降低卷积层对位置的敏感性；一定程度减少计算。\n",
    "\n",
    "## 最大池化层和平均池化层\n",
    "\n",
    "与卷积层类似，池化层运算符由一个固定形状的窗口组成，该窗口根据其步幅大小在输入的所有区域上滑动，为固定形状窗口遍历的每个位置计算一个输出。\n",
    "然而，不同于卷积层中的输入与卷积核之间的互相关计算，**池化层不包含参数**。\n",
    "相反，池运算符是确定性的，我们通常计算池化窗口中所有元素的最大值或平均值。这些操作分别称为*最大池化层*（maximum pooling）和*平均池化层*（average pooling）。\n",
    "\n",
    "在这两种情况下，与互相关运算符一样，池化窗口从输入张量的左上角开始，从左往右、从上往下的在输入张量内滑动。在池化窗口到达的每个位置，它计算该窗口中输入子张量的最大值或平均值。计算最大值或平均值是取决于使用了最大池化层还是平均池化层。\n",
    "\n",
    "![池化窗口形状为 $2\\times 2$ 的最大池化层。着色部分是第一个输出元素，以及用于计算这个输出的输入元素: $\\max(0, 1, 3, 4)=4$.](http://d2l.ai/_images/pooling.svg)\n",
    "上图中的输出张量的高度为$2$，宽度为$2$。这四个元素为每个池化窗口中的最大值：\n",
    "\n",
    "$$\n",
    "\\max(0, 1, 3, 4)=4,\\\\\n",
    "\\max(1, 2, 4, 5)=5,\\\\\n",
    "\\max(3, 4, 6, 7)=7,\\\\\n",
    "\\max(4, 5, 7, 8)=8.\\\\\n",
    "$$\n",
    "\n",
    "池化窗口形状为$p \\times q$的池化层称为$p \\times q$池化层，池化操作称为$p \\times q$池化。\n",
    "\n",
    "回到本节开头提到的对象边缘检测示例，现在我们将使用卷积层的输出作为$2\\times 2$最大池化的输入。\n",
    "设置卷积层输入为`X`，池化层输出为`Y`。\n",
    "无论`X[i, j]`和`X[i, j + 1]`的值是否不同，或`X[i, j + 1]`和`X[i, j + 2]`的值是否不同，池化层始终输出`Y[i, j] = 1`。\n",
    "也就是说，使用$2\\times 2$最大池化层，即使在高度或宽度上移动一个元素，卷积层仍然可以识别到模式。\n",
    "\n",
    "在下面的代码中的`pool2d`函数，我们(**实现池化层的前向传播**)。然而，这里我们没有卷积核，输出为输入中每个区域的最大值或平均值。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "origin_pos": 2,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "from torch import nn\n",
    "from d2l import torch as d2l"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "origin_pos": 3,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "def pool2d(X, pool_size, mode='max'):\n",
    "    p_h, p_w = pool_size\n",
    "    Y = torch.zeros((X.shape[0] - p_h + 1, X.shape[1] - p_w + 1))\n",
    "    for i in range(Y.shape[0]):\n",
    "        for j in range(Y.shape[1]):  # 枚举输出的每个位置，[i,j]对应输入的位置[i至i+p_h,j至j+p_w]\n",
    "            if mode == 'max':  # 最大池化\n",
    "                Y[i, j] = X[i: i + p_h, j: j + p_w].max()  # max函数返回最大值\n",
    "            elif mode == 'avg':  # 平均池化\n",
    "                Y[i, j] = X[i: i + p_h, j: j + p_w].mean()  # mean函数返回平均值\n",
    "    return Y"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 5
   },
   "source": [
    "我们可以构建上图中的输入张量`X`，[**验证二维最大池化层的输出**]。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "origin_pos": 6,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[4., 5.],\n",
       "        [7., 8.]])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = torch.tensor([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]])\n",
    "pool2d(X, (2, 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 7
   },
   "source": [
    "此外，我们还可以(**验证平均池化层**)。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "origin_pos": 8,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[2., 3.],\n",
       "        [5., 6.]])"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pool2d(X, (2, 2), 'avg')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 9
   },
   "source": [
    "## 填充和步幅\n",
    "\n",
    "与卷积层一样，池化层也可以改变输出形状。和以前一样，我们可以通过填充和步幅以获得所需的输出形状。\n",
    "下面，我们用深度学习框架中内置的二维最大池化层，来演示池化层中填充和步幅的使用。\n",
    "我们首先构造了一个输入张量`X`，它有四个维度，其中样本数和通道数都是1。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "origin_pos": 11,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[[ 0.,  1.,  2.,  3.],\n",
       "          [ 4.,  5.,  6.,  7.],\n",
       "          [ 8.,  9., 10., 11.],\n",
       "          [12., 13., 14., 15.]]]])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = torch.arange(16, dtype=torch.float32).reshape(\n",
    "    (1, 1, 4, 4))  # 维度[batch_size，通道数，H，W]\n",
    "X"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 13
   },
   "source": [
    "默认情况下，(**深度学习框架中的步幅与池化窗口的大小相同**)。\n",
    "因此，如果我们使用形状为`(3, 3)`的池化窗口，那么默认情况下，我们得到的步幅形状为`(3, 3)`。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "origin_pos": 15,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[[10.]]]])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pool2d = nn.MaxPool2d(3)\n",
    "pool2d(X)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 17
   },
   "source": [
    "[**填充和步幅可以手动设定**]。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "origin_pos": 19,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[[ 5.,  7.],\n",
       "          [13., 15.]]]])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pool2d = nn.MaxPool2d(3, padding=1, stride=2)\n",
    "pool2d(X)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 22,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "当然，我们可以(**设定一个任意大小的矩形池化窗口，并分别设定填充和步幅的高度和宽度**)。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "origin_pos": 25,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[[ 5.,  7.],\n",
       "          [13., 15.]]]])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pool2d = nn.MaxPool2d((2, 3), stride=(2, 3), padding=(0, 1))\n",
    "pool2d(X)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 27
   },
   "source": [
    "## 多个通道\n",
    "\n",
    "在处理多通道输入数据时，[**池化层在每个输入通道上单独运算**]，而不是像卷积层一样在通道上对输入进行汇总。\n",
    "这意味着池化层的输出通道数与输入通道数相同。\n",
    "下面，我们将在通道维度上连结张量`X`和`X + 1`，以构建具有2个通道的输入。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "origin_pos": 29,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[[ 0.,  1.,  2.,  3.],\n",
       "          [ 4.,  5.,  6.,  7.],\n",
       "          [ 8.,  9., 10., 11.],\n",
       "          [12., 13., 14., 15.]],\n",
       "\n",
       "         [[ 1.,  2.,  3.,  4.],\n",
       "          [ 5.,  6.,  7.,  8.],\n",
       "          [ 9., 10., 11., 12.],\n",
       "          [13., 14., 15., 16.]]]])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = torch.cat((X, X + 1), 1)  # 在第一个维度也就是通道维度拼接\n",
    "X"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 31
   },
   "source": [
    "如下所示，池化后输出通道的数量仍然是2。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "origin_pos": 33,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[[ 5.,  7.],\n",
       "          [13., 15.]],\n",
       "\n",
       "         [[ 6.,  8.],\n",
       "          [14., 16.]]]])"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pool2d = nn.MaxPool2d(3, padding=1, stride=2)\n",
    "pool2d(X)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 36
   },
   "source": [
    "## 小结\n",
    "\n",
    "* 对于给定输入元素，最大池化层会输出该窗口内的最大值，平均池化层会输出该窗口内的平均值。\n",
    "* 池化层的主要优点之一是减轻卷积层对位置的过度敏感。\n",
    "* 我们可以指定池化层的填充和步幅。\n",
    "* 使用最大池化层以及大于1的步幅，可减少空间维度（如高度和宽度）。\n",
    "* 池化层的输出通道数与输入通道数相同。\n",
    "\n",
    "## 问题和练习\n",
    "\n",
    "1. 你能将平均池化层作为卷积层的特殊情况实现吗？\n",
    ">设卷积层大小是$m\\times n$，卷积层里面每个元素参数是$\\dfrac{1} {m\\times n}$，这样就是一个平均池化层作为卷积层的实现\n",
    "1. 假设池化层的输入大小为$c\\times h\\times w$，则汇聚窗口的形状为$p_h\\times p_w$，填充为$(p_h, p_w)$，步幅为$(s_h, s_w)$。这个池化层的计算成本是多少？\n",
    ">$ c\\times \\left \\lfloor \\dfrac {h-p_h+s_h}{s_h}\\right \\rfloor \\times \\left \\lfloor \\dfrac {w-p_w+s_w}{s_w}\\right \\rfloor $\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 38,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.12"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
